#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

from pymongo import MongoClient
from tqdm import tqdm


def getContext(collection, uni_org):
    result = []
    for item in collection.find({"country": "China", "uni_org": uni_org}, {"_id": 0, "org": 1}).limit(10):
        result.append(item["org"])
    return result


if __name__ == "__main__":
    connection_destination = MongoClient("localhost", 27017)
    collection_destination = connection_destination["mcp"]["organization_source"]

    connection_source = MongoClient("10.188.188.22", 27017)
    collection_bulk = connection_source["org_bulk_curation"]["org_bulk_curation_china_k_5_20160812"]
    collection_organization = connection_source["organization"]["organization"]

    for result in tqdm(collection_bulk.find({}, {"_id": 0, "group_id": 1, "org_name": 1, "org_id": 1})):
        group_id = str(result["group_id"])
        name = result["org_name"]
        org_id = str(result["org_id"])
        context = getContext(collection_organization, name)
        collection_destination.update_one({"group_id": group_id},
                                          {"$addToSet": {"orgs": {"org_id": org_id, "name": name, "context": context,
                                                                  "status": "normal"}}},
                                          upsert=True)

    connection_destination.close()
    connection_source.close()
